<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Brand;
use App\Models\BusinessMember;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;

class BrandController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Brand(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('brands_name');
            $grid->column('brands_images')->image();
            $grid->column('member_id', '绑定账号')->display(function ($member) {
                return BusinessMember::find($member)->username;
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Brand(), function (Show $show) {
            $show->field('id');
            $show->field('brands_name');
            $show->field('brands_images');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Brand(), function (Form $form) {
            $form->display('id');
            $form->text('brands_name');
            $form->image('brands_images')->uniqueName();
            $form->select('member_id', '绑定品牌商')->options(function ($id) {

                $memberInfo = BusinessMember::find($id);
                if ($memberInfo) {
                    return [$memberInfo->id => $memberInfo->username];
                }

            })->ajax('/business/get-members');

            // 红包模式
            $form->radio('envelope_type', '红包模式')
                ->when('regular', function (Form $form) {
                    $form->currency('envelope_money', '红包金额')->symbol('￥');
                })
                ->when('random', function (Form $form) {
                    $form->range('start_money', 'end_money', '金额范围')
                        ->help('包含首尾值');
                })
                ->options([
                    'regular' => '固定',
                    'random' => '随机'
                ])
                ->default('regular');


            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    // 获取可用品牌方
    public function getBrands(Request $request)
    {
        $q = $request->get('q');
        return \App\Models\Brand::where('brands_name', 'like', "%{$q}%")
            ->paginate(null, ['id', 'brands_name as text']);
    }
}
